<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>竹笛长音练习助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4ade80', // 清新的绿色，代表成长和自然
                        secondary: '#3b82f6', // 蓝色，代表专注和平静
                        accent: '#f59e0b', // 温暖的橙色，用于强调
                        neutral: '#f3f4f6', // 浅灰色背景
                    },
                    fontFamily: {
                        rounded: ['"Comic Sans MS"', '"Marker Felt"', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .pulse-animation {
                animation: pulse 1s infinite;
            }
            .beat-animation {
                animation: beat 1s infinite;
            }
            .float {
                animation: float 3s ease-in-out infinite;
            }
        }
        
        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
                opacity: 1;
            }
            50% {
                transform: scale(1.1);
                opacity: 0.8;
            }
        }
        
        @keyframes beat {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.3);
            }
        }
        
        @keyframes float {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-10px);
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-green-50 to-blue-50 min-h-screen font-rounded text-gray-800">
    <!-- 页面头部 -->
    <header class="bg-white/80 backdrop-blur-md shadow-sm py-4 px-6 sticky top-0 z-50">
        <div class="container mx-auto flex justify-between items-center">
            <div class="flex items-center gap-3">
                <i class="fa fa-music text-primary text-3xl float"></i>
                <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-primary">竹笛长音练习</h1>
            </div>
            <div class="hidden md:flex items-center gap-4">
                <button id="helpBtn" class="flex items-center gap-2 bg-blue-100 hover:bg-blue-200 text-blue-800 px-4 py-2 rounded-full transition-all">
                    <i class="fa fa-question-circle"></i>
                    <span>帮助</span>
                </button>
                <button id="settingsBtn" class="flex items-center gap-2 bg-yellow-100 hover:bg-yellow-200 text-yellow-800 px-4 py-2 rounded-full transition-all">
                    <i class="fa fa-cog"></i>
                    <span>设置</span>
                </button>
            </div>
            <button class="md:hidden text-2xl" id="mobileMenuBtn">
                <i class="fa fa-bars"></i>
            </button>
        </div>
        
        <!-- 移动端菜单 -->
        <div id="mobileMenu" class="hidden md:hidden mt-4 bg-white rounded-lg shadow-md p-4">
            <button id="mobileHelpBtn" class="flex items-center gap-2 w-full justify-start bg-blue-100 text-blue-800 px-4 py-2 rounded-full mb-2">
                <i class="fa fa-question-circle"></i>
                <span>帮助</span>
            </button>
            <button id="mobileSettingsBtn" class="flex items-center gap-2 w-full justify-start bg-yellow-100 text-yellow-800 px-4 py-2 rounded-full">
                <i class="fa fa-cog"></i>
                <span>设置</span>
            </button>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <!-- 练习介绍 -->
        <section class="bg-white rounded-2xl shadow-md p-6 mb-8 transform transition-all hover:shadow-lg">
            <h2 class="text-2xl font-bold text-secondary mb-4 flex items-center">
                <i class="fa fa-info-circle mr-2"></i>长音练习指南
            </h2>
            <p class="text-gray-700 mb-3">长音练习是竹笛学习的基础，能帮助你掌握气息控制和音准。</p>
            <ul class="list-disc list-inside text-gray-700 space-y-1 ml-2">
                <li>保持稳定的气息，让声音持续且平稳</li>
                <li>跟随节拍器的节奏，感受稳定的时长</li>
                <li>每个音尝试保持相同的音量和音色</li>
                <li>每天练习5-10分钟，坚持会有进步哦！</li>
            </ul>
        </section>
        
        <!-- 节拍器控制区 -->
        <section class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
            <!-- 节拍器显示 -->
            <div class="lg:col-span-2 bg-white rounded-2xl shadow-md p-6 flex flex-col items-center justify-center">
                <h2 class="text-2xl font-bold text-secondary mb-6">节拍器</h2>
                
                <div class="relative w-64 h-64 mb-8 flex items-center justify-center">
                    <!-- 圆形背景 -->
                    <div class="absolute inset-0 rounded-full border-8 border-primary/20"></div>
                    <div class="absolute inset-4 rounded-full border-4 border-primary/30"></div>
                    
                    <!-- 节拍指示器 -->
                    <div id="beatIndicator" class="w-20 h-20 bg-primary rounded-full flex items-center justify-center text-white text-2xl font-bold">
                        <span id="beatCount">1</span>
                    </div>
                    
                    <!-- 装饰性标记 -->
                    <div class="absolute top-0 w-full flex justify-center">
                        <div class="w-3 h-8 bg-secondary rounded-full"></div>
                    </div>
                    <div class="absolute bottom-0 w-full flex justify-center">
                        <div class="w-3 h-8 bg-secondary rounded-full"></div>
                    </div>
                    <div class="absolute left-0 h-full w-full flex items-center">
                        <div class="w-8 h-3 bg-secondary rounded-full"></div>
                    </div>
                    <div class="absolute right-0 h-full w-full flex items-center justify-end">
                        <div class="w-8 h-3 bg-secondary rounded-full"></div>
                    </div>
                </div>
                
                <!-- 拍速控制 -->
                <div class="w-full max-w-md">
                    <div class="flex justify-between items-center mb-2">
                        <label for="tempo" class="font-bold text-gray-700">速度: <span id="tempoValue">60</span> BPM</label>
                        <div class="flex gap-2">
                            <button id="decreaseTempo" class="w-8 h-8 bg-gray-200 hover:bg-gray-300 rounded-full flex items-center justify-center transition-all">
                                <i class="fa fa-minus"></i>
                            </button>
                            <button id="increaseTempo" class="w-8 h-8 bg-gray-200 hover:bg-gray-300 rounded-full flex items-center justify-center transition-all">
                                <i class="fa fa-plus"></i>
                            </button>
                        </div>
                    </div>
                    <input 
                        type="range" 
                        id="tempo" 
                        min="40" 
                        max="120" 
                        value="60" 
                        class="w-full h-3 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary"
                    >
                </div>
                
                <!-- 拍号选择 -->
                <div class="w-full max-w-md mt-6">
                    <label class="font-bold text-gray-700 block mb-2">拍号</label>
                    <div class="grid grid-cols-3 gap-2">
                        <button class="time-signature-btn bg-primary text-white py-2 rounded-lg transition-all" data-signature="4">4/4</button>
                        <button class="time-signature-btn bg-gray-200 hover:bg-gray-300 py-2 rounded-lg transition-all" data-signature="3">3/4</button>
                        <button class="time-signature-btn bg-gray-200 hover:bg-gray-300 py-2 rounded-lg transition-all" data-signature="2">2/4</button>
                    </div>
                </div>
            </div>
            
            <!-- 练习控制 -->
            <div class="bg-white rounded-2xl shadow-md p-6 flex flex-col">
                <h2 class="text-2xl font-bold text-secondary mb-6">练习控制</h2>
                
                <!-- 时长设置 -->
                <div class="mb-6">
                    <label class="font-bold text-gray-700 block mb-2">练习时长</label>
                    <div class="grid grid-cols-3 gap-2">
                        <button class="duration-btn bg-primary text-white py-3 rounded-lg transition-all" data-duration="1">1分钟</button>
                        <button class="duration-btn bg-gray-200 hover:bg-gray-300 py-3 rounded-lg transition-all" data-duration="3">3分钟</button>
                        <button class="duration-btn bg-gray-200 hover:bg-gray-300 py-3 rounded-lg transition-all" data-duration="5">5分钟</button>
                    </div>
                </div>
                
                <!-- 音长设置 -->
                <div class="mb-6">
                    <label class="font-bold text-gray-700 block mb-2">每个音时长</label>
                    <div class="grid grid-cols-3 gap-2">
                        <button class="note-length-btn bg-primary text-white py-3 rounded-lg transition-all" data-length="2">2拍</button>
                        <button class="note-length-btn bg-gray-200 hover:bg-gray-300 py-3 rounded-lg transition-all" data-length="4">4拍</button>
                        <button class="note-length-btn bg-gray-200 hover:bg-gray-300 py-3 rounded-lg transition-all" data-length="8">8拍</button>
                    </div>
                </div>
                
                <!-- 开始/停止按钮 -->
                <div class="mt-auto">
                    <button id="startBtn" class="w-full bg-green-500 hover:bg-green-600 text-white py-4 rounded-xl text-xl font-bold transition-all flex items-center justify-center gap-2">
                        <i class="fa fa-play"></i>
                        <span>开始练习</span>
                    </button>
                    <button id="stopBtn" class="w-full bg-red-500 hover:bg-red-600 text-white py-4 rounded-xl text-xl font-bold transition-all mt-3 flex items-center justify-center gap-2 hidden">
                        <i class="fa fa-stop"></i>
                        <span>停止练习</span>
                    </button>
                </div>
                
                <!-- 计时器显示 -->
                <div class="mt-6 text-center">
                    <h3 class="text-gray-600 mb-1">剩余时间</h3>
                    <div id="timerDisplay" class="text-3xl font-bold text-accent">01:00</div>
                </div>
            </div>
        </section>
        
        <!-- 练习提示 -->
        <section class="bg-white rounded-2xl shadow-md p-6 mb-8">
            <h2 class="text-2xl font-bold text-secondary mb-4 flex items-center">
                <i class="fa fa-lightbulb-o mr-2"></i>练习小贴士
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="bg-green-50 p-4 rounded-xl border border-green-100">
                    <h3 class="font-bold text-green-800 mb-2">正确姿势</h3>
                    <p class="text-gray-700">保持身体挺直，肩膀放松，手臂自然弯曲，笛子与身体成45度角。</p>
                </div>
                <div class="bg-blue-50 p-4 rounded-xl border border-blue-100">
                    <h3 class="font-bold text-blue-800 mb-2">呼吸方法</h3>
                    <p class="text-gray-700">用腹部呼吸，吸气时腹部鼓起，呼气时保持稳定，不要耸肩。</p>
                </div>
                <div class="bg-yellow-50 p-4 rounded-xl border border-yellow-100">
                    <h3 class="font-bold text-yellow-800 mb-2">每日练习</h3>
                    <p class="text-gray-700">每天固定时间练习，短时间多次练习比长时间一次练习效果更好。</p>
                </div>
                <div class="bg-purple-50 p-4 rounded-xl border border-purple-100">
                    <h3 class="font-bold text-purple-800 mb-2">专注聆听</h3>
                    <p class="text-gray-700">仔细听自己吹出的声音，努力让它保持平稳、清晰和饱满。</p>
                </div>
            </div>
        </section>
        
        <!-- 成就展示 -->
        <section class="bg-white rounded-2xl shadow-md p-6">
            <h2 class="text-2xl font-bold text-secondary mb-4 flex items-center">
                <i class="fa fa-trophy mr-2"></i>我的成就
            </h2>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="bg-neutral rounded-xl p-4 text-center">
                    <div class="w-16 h-16 bg-primary/20 rounded-full flex items-center justify-center mx-auto mb-2">
                        <i class="fa fa-calendar text-primary text-2xl"></i>
                    </div>
                    <h3 class="font-bold text-gray-700 mb-1">连续练习</h3>
                    <p class="text-2xl font-bold text-accent" id="streakCount">0</p>
                    <p class="text-sm text-gray-500">天</p>
                </div>
                <div class="bg-neutral rounded-xl p-4 text-center">
                    <div class="w-16 h-16 bg-secondary/20 rounded-full flex items-center justify-center mx-auto mb-2">
                        <i class="fa fa-clock-o text-secondary text-2xl"></i>
                    </div>
                    <h3 class="font-bold text-gray-700 mb-1">总时长</h3>
                    <p class="text-2xl font-bold text-accent" id="totalTime">0</p>
                    <p class="text-sm text-gray-500">分钟</p>
                </div>
                <div class="bg-neutral rounded-xl p-4 text-center">
                    <div class="w-16 h-16 bg-accent/20 rounded-full flex items-center justify-center mx-auto mb-2">
                        <i class="fa fa-star text-accent text-2xl"></i>
                    </div>
                    <h3 class="font-bold text-gray-700 mb-1">获得星星</h3>
                    <p class="text-2xl font-bold text-accent" id="starsCount">0</p>
                    <p class="text-sm text-gray-500">颗</p>
                </div>
                <div class="bg-neutral rounded-xl p-4 text-center">
                    <div class="w-16 h-16 bg-purple-200 rounded-full flex items-center justify-center mx-auto mb-2">
                        <i class="fa fa-music text-purple-500 text-2xl"></i>
                    </div>
                    <h3 class="font-bold text-gray-700 mb-1">完成练习</h3>
                    <p class="text-2xl font-bold text-accent" id="completedCount">0</p>
                    <p class="text-sm text-gray-500">次</p>
                </div>
            </div>
        </section>
    </main>

    <footer class="bg-gray-800 text-white py-8 mt-12">
        <div class="container mx-auto px-4">
            <div class="text-center">
                <h3 class="text-xl font-bold mb-4">竹笛长音练习助手</h3>
                <p class="text-gray-400 mb-6">让竹笛练习变得更有趣、更有效</p>
                <div class="flex justify-center gap-4">
                    <button class="w-10 h-10 rounded-full bg-gray-700 hover:bg-gray-600 flex items-center justify-center transition-all">
                        <i class="fa fa-volume-up"></i>
                    </button>
                    <button class="w-10 h-10 rounded-full bg-gray-700 hover:bg-gray-600 flex items-center justify-center transition-all">
                        <i class="fa fa-moon-o"></i>
                    </button>
                    <button class="w-10 h-10 rounded-full bg-gray-700 hover:bg-gray-600 flex items-center justify-center transition-all">
                        <i class="fa fa-share-alt"></i>
                    </button>
                </div>
                <p class="text-gray-500 text-sm mt-6">© 2023 竹笛练习助手 - 为年轻音乐家设计</p>
            </div>
        </div>
    </footer>

    <!-- 帮助模态框 -->
    <div id="helpModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center hidden">
        <div class="bg-white rounded-2xl max-w-md w-full max-h-[90vh] overflow-y-auto p-6 m-4">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-2xl font-bold text-secondary">使用帮助</h3>
                <button id="closeHelpBtn" class="text-gray-500 hover:text-gray-700 text-xl">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="space-y-4 text-gray-700">
                <div>
                    <h4 class="font-bold text-lg mb-1">如何开始练习？</h4>
                    <p>1. 选择合适的练习时长（1分钟、3分钟或5分钟）</p>
                    <p>2. 选择每个音的持续时间（2拍、4拍或8拍）</p>
                    <p>3. 调整节拍器速度（40-120 BPM）</p>
                    <p>4. 点击"开始练习"按钮</p>
                </div>
                <div>
                    <h4 class="font-bold text-lg mb-1">节拍器使用</h4>
                    <p>节拍器会显示当前节拍，帮助你保持稳定的节奏。跟随节拍吹奏长音，每个音保持指定的拍数。</p>
                </div>
                <div>
                    <h4 class="font-bold text-lg mb-1">练习技巧</h4>
                    <p>• 保持稳定的气息，不要在音的末尾减弱</p>
                    <p>• 注意聆听自己的声音，确保音高准确</p>
                    <p>• 每天坚持练习，进步会更快</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 设置模态框 -->
    <div id="settingsModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center hidden">
        <div class="bg-white rounded-2xl max-w-md w-full p-6 m-4">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-2xl font-bold text-secondary">设置</h3>
                <button id="closeSettingsBtn" class="text-gray-500 hover:text-gray-700 text-xl">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="space-y-4">
                <div>
                    <label class="font-bold text-gray-700 block mb-2">节拍声音</label>
                    <div class="flex items-center gap-2">
                        <button class="w-10 h-10 bg-gray-200 hover:bg-gray-300 rounded-full flex items-center justify-center transition-all" id="testSoundBtn">
                            <i class="fa fa-volume-up"></i>
                        </button>
                        <input type="range" min="0" max="100" value="70" class="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                    </div>
                </div>
                <div>
                    <label class="font-bold text-gray-700 block mb-2">视觉提示</label>
                    <div class="flex items-center gap-2">
                        <span>关闭</span>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" value="" class="sr-only peer" checked>
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                        </label>
                        <span>开启</span>
                    </div>
                </div>
                <div>
                    <label class="font-bold text-gray-700 block mb-2">音效提示</label>
                    <div class="flex items-center gap-2">
                        <span>关闭</span>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" value="" class="sr-only peer" checked>
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                        </label>
                        <span>开启</span>
                    </div>
                </div>
                <button id="resetProgressBtn" class="w-full bg-red-100 hover:bg-red-200 text-red-800 py-2 rounded-lg transition-all mt-4">
                    重置练习进度
                </button>
            </div>
        </div>
    </div>

    <!-- 完成练习提示 -->
    <div id="completionModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center hidden">
        <div class="bg-white rounded-2xl max-w-md w-full p-6 m-4 text-center">
            <div class="w-20 h-20 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fa fa-trophy text-yellow-500 text-4xl"></i>
            </div>
            <h3 class="text-2xl font-bold text-secondary mb-2">太棒了！</h3>
            <p class="text-gray-700 mb-6">你完成了今天的长音练习</p>
            <p class="text-xl text-accent font-bold mb-6">+1 星星</p>
            <button id="closeCompletionBtn" class="bg-primary hover:bg-primary/90 text-white py-3 px-8 rounded-xl font-bold transition-all">
                继续努力
            </button>
        </div>
    </div>

    <script>
        // 音频上下文和节拍声音
        let audioContext;
        let beatOscillator;
        let beatGain;
        
        // 应用状态
        const state = {
            isPlaying: false,
            tempo: 60, // BPM
            timeSignature: 4, // 4/4拍
            duration: 1, // 练习时长（分钟）
            noteLength: 2, // 每个音的拍数
            currentBeat: 1,
            timer: null,
            remainingTime: 60, // 秒
            totalPracticeTime: 0, // 总练习时间（分钟）
            completedPractices: 0, // 完成的练习次数
            streak: 0, // 连续练习天数
            stars: 0 // 获得的星星数量
        };
        
        // DOM元素
        const elements = {
            beatIndicator: document.getElementById('beatIndicator'),
            beatCount: document.getElementById('beatCount'),
            tempoSlider: document.getElementById('tempo'),
            tempoValue: document.getElementById('tempoValue'),
            decreaseTempo: document.getElementById('decreaseTempo'),
            increaseTempo: document.getElementById('increaseTempo'),
            timeSignatureBtns: document.querySelectorAll('.time-signature-btn'),
            durationBtns: document.querySelectorAll('.duration-btn'),
            noteLengthBtns: document.querySelectorAll('.note-length-btn'),
            startBtn: document.getElementById('startBtn'),
            stopBtn: document.getElementById('stopBtn'),
            timerDisplay: document.getElementById('timerDisplay'),
            helpBtn: document.getElementById('helpBtn'),
            mobileHelpBtn: document.getElementById('mobileHelpBtn'),
            settingsBtn: document.getElementById('settingsBtn'),
            mobileSettingsBtn: document.getElementById('mobileSettingsBtn'),
            mobileMenuBtn: document.getElementById('mobileMenuBtn'),
            mobileMenu: document.getElementById('mobileMenu'),
            helpModal: document.getElementById('helpModal'),
            closeHelpBtn: document.getElementById('closeHelpBtn'),
            settingsModal: document.getElementById('settingsModal'),
            closeSettingsBtn: document.getElementById('closeSettingsBtn'),
            testSoundBtn: document.getElementById('testSoundBtn'),
            resetProgressBtn: document.getElementById('resetProgressBtn'),
            completionModal: document.getElementById('completionModal'),
            closeCompletionModal: document.getElementById('closeCompletionBtn'),
            streakCount: document.getElementById('streakCount'),
            totalTime: document.getElementById('totalTime'),
            starsCount: document.getElementById('starsCount'),
            completedCount: document.getElementById('completedCount')
        };
        
        // 初始化应用
        function init() {
            // 从本地存储加载进度
            loadProgress();
            
            // 事件监听
            elements.tempoSlider.addEventListener('input', updateTempo);
            elements.decreaseTempo.addEventListener('click', () => {
                elements.tempoSlider.value = Math.max(40, parseInt(elements.tempoSlider.value) - 5);
                updateTempo();
            });
            elements.increaseTempo.addEventListener('click', () => {
                elements.tempoSlider.value = Math.min(120, parseInt(elements.tempoSlider.value) + 5);
                updateTempo();
            });
            
            elements.timeSignatureBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    elements.timeSignatureBtns.forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-200', 'hover:bg-gray-300');
                    });
                    btn.classList.remove('bg-gray-200', 'hover:bg-gray-300');
                    btn.classList.add('bg-primary', 'text-white');
                    state.timeSignature = parseInt(btn.dataset.signature);
                });
            });
            
            elements.durationBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    elements.durationBtns.forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-200', 'hover:bg-gray-300');
                    });
                    btn.classList.remove('bg-gray-200', 'hover:bg-gray-300');
                    btn.classList.add('bg-primary', 'text-white');
                    state.duration = parseInt(btn.dataset.duration);
                    state.remainingTime = state.duration * 60;
                    updateTimerDisplay();
                });
            });
            
            elements.noteLengthBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    elements.noteLengthBtns.forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-200', 'hover:bg-gray-300');
                    });
                    btn.classList.remove('bg-gray-200', 'hover:bg-gray-300');
                    btn.classList.add('bg-primary', 'text-white');
                    state.noteLength = parseInt(btn.dataset.length);
                });
            });
            
            elements.startBtn.addEventListener('click', startPractice);
            elements.stopBtn.addEventListener('click', stopPractice);
            
            // 菜单和模态框控制
            elements.mobileMenuBtn.addEventListener('click', () => {
                elements.mobileMenu.classList.toggle('hidden');
            });
            
            elements.helpBtn.addEventListener('click', () => {
                elements.helpModal.classList.remove('hidden');
            });
            
            elements.mobileHelpBtn.addEventListener('click', () => {
                elements.mobileMenu.classList.add('hidden');
                elements.helpModal.classList.remove('hidden');
            });
            
            elements.closeHelpBtn.addEventListener('click', () => {
                elements.helpModal.classList.add('hidden');
            });
            
            elements.settingsBtn.addEventListener('click', () => {
                elements.settingsModal.classList.remove('hidden');
            });
            
            elements.mobileSettingsBtn.addEventListener('click', () => {
                elements.mobileMenu.classList.add('hidden');
                elements.settingsModal.classList.remove('hidden');
            });
            
            elements.closeSettingsBtn.addEventListener('click', () => {
                elements.settingsModal.classList.add('hidden');
            });
            
            elements.testSoundBtn.addEventListener('click', playTestSound);
            elements.resetProgressBtn.addEventListener('click', resetProgress);
            elements.closeCompletionModal.addEventListener('click', () => {
                elements.completionModal.classList.add('hidden');
            });
            
            // 点击模态框外部关闭
            elements.helpModal.addEventListener('click', (e) => {
                if (e.target === elements.helpModal) {
                    elements.helpModal.classList.add('hidden');
                }
            });
            
            elements.settingsModal.addEventListener('click', (e) => {
                if (e.target === elements.settingsModal) {
                    elements.settingsModal.classList.add('hidden');
                }
            });
            
            elements.completionModal.addEventListener('click', (e) => {
                if (e.target === elements.completionModal) {
                    elements.completionModal.classList.add('hidden');
                }
            });
            
            // 初始化计时器显示
            updateTimerDisplay();
        }
        
        // 更新节拍速度
        function updateTempo() {
            state.tempo = parseInt(elements.tempoSlider.value);
            elements.tempoValue.textContent = state.tempo;
            
            // 如果正在播放，重新启动计时器以应用新速度
            if (state.isPlaying) {
                clearInterval(state.timer);
                startTimer();
            }
        }
        
        // 开始练习
        function startPractice() {
            state.isPlaying = true;
            elements.startBtn.classList.add('hidden');
            elements.stopBtn.classList.remove('hidden');
            
            // 初始化音频上下文（需要用户交互）
            if (!audioContext) {
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                beatGain = audioContext.createGain();
                beatGain.gain.value = 0.7;
                beatGain.connect(audioContext.destination);
            }
            
            // 开始节拍计时器
            startTimer();
        }
        
        // 停止练习
        function stopPractice() {
            state.isPlaying = false;
            elements.startBtn.classList.remove('hidden');
            elements.stopBtn.classList.add('hidden');
            
            // 清除计时器
            clearInterval(state.timer);
            
            // 重置节拍指示器
            elements.beatIndicator.classList.remove('beat-animation');
        }
        
        // 启动节拍计时器
        function startTimer() {
            // 计算每拍的毫秒数
            const msPerBeat = 60000 / state.tempo;
            
            // 清除现有计时器
            if (state.timer) {
                clearInterval(state.timer);
            }
            
            // 更新节拍
            function updateBeat() {
                // 播放节拍声音
                playBeatSound();
                
                // 更新视觉节拍指示器
                elements.beatCount.textContent = state.currentBeat;
                elements.beatIndicator.classList.add('beat-animation');
                setTimeout(() => {
                    elements.beatIndicator.classList.remove('beat-animation');
                }, 200);
                
                // 检查是否完成一个音符周期
                if (state.currentBeat === state.noteLength) {
                    // 可以在这里添加换音提示
                }
                
                // 增加节拍计数或重置
                state.currentBeat = state.currentBeat % state.timeSignature + 1;
                
                // 更新剩余时间（每秒更新一次）
                if (Math.floor(msPerBeat) === 1000) {
                    updateRemainingTime();
                }
            }
            
            // 立即更新一次节拍
            updateBeat();
            
            // 设置计时器
            state.timer = setInterval(updateBeat, msPerBeat);
            
            // 如果节拍不是每秒一次，单独更新剩余时间
            if (Math.floor(msPerBeat) !== 1000) {
                setInterval(updateRemainingTime, 1000);
            }
        }
        
        // 播放节拍声音
        function playBeatSound() {
            if (!audioContext) return;
            
            // 确保音频上下文处于运行状态
            if (audioContext.state === 'suspended') {
                audioContext.resume();
            }
            
            // 创建振荡器
            beatOscillator = audioContext.createOscillator();
            
            // 第一拍使用不同的音高，使其更突出
            beatOscillator.frequency.value = state.currentBeat === 1 ? 880 : 440;
            
            beatOscillator.type = 'sine';
            beatOscillator.connect(beatGain);
            
            // 开始并在短时间后停止声音
            beatOscillator.start();
            beatOscillator.stop(audioContext.currentTime + 0.1);
        }
        
        // 播放测试声音
        function playTestSound() {
            if (!audioContext) {
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                beatGain = audioContext.createGain();
                beatGain.gain.value = 0.7;
                beatGain.connect(audioContext.destination);
            } else if (audioContext.state === 'suspended') {
                audioContext.resume();
            }
            
            const oscillator = audioContext.createOscillator();
            oscillator.frequency.value = 660;
            oscillator.type = 'sine';
            oscillator.connect(beatGain);
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.3);
        }
        
        // 更新剩余时间
        function updateRemainingTime() {
            if (!state.isPlaying) return;
            
            state.remainingTime--;
            updateTimerDisplay();
            
            // 检查是否练习结束
            if (state.remainingTime <= 0) {
                completePractice();
            }
        }
        
        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(state.remainingTime / 60);
            const seconds = state.remainingTime % 60;
            elements.timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
        
        // 完成练习
        function completePractice() {
            stopPractice();
            
            // 更新练习统计
            state.totalPracticeTime += state.duration;
            state.completedPractices++;
            state.stars++;
            
            // 检查连续练习
            updateStreak();
            
            // 保存进度
            saveProgress();
            
            // 更新UI
            updateProgressDisplay();
            
            // 显示完成提示
            elements.completionModal.classList.remove('hidden');
            
            // 重置剩余时间
            state.remainingTime = state.duration * 60;
            updateTimerDisplay();
        }
        
        // 更新连续练习天数
        function updateStreak() {
            const lastPracticeDate = localStorage.getItem('lastPracticeDate');
            const today = new Date().toDateString();
            
            if (!lastPracticeDate) {
                // 第一次练习
                state.streak = 1;
            } else if (lastPracticeDate === today) {
                // 今天已经练习过
                // 不增加连续天数
            } else {
                const yesterday = new Date();
                yesterday.setDate(yesterday.getDate() - 1);
                
                if (lastPracticeDate === yesterday.toDateString()) {
                    // 连续两天练习
                    state.streak++;
                } else {
                    // 中断了，重新开始计数
                    state.streak = 1;
                }
            }
            
            // 保存今天的日期
            localStorage.setItem('lastPracticeDate', today);
        }
        
        // 加载练习进度
        function loadProgress() {
            const savedTotalTime = localStorage.getItem('totalPracticeTime');
            const savedCompleted = localStorage.getItem('completedPractices');
            const savedStreak = localStorage.getItem('practiceStreak');
            const savedStars = localStorage.getItem('practiceStars');
            
            if (savedTotalTime) state.totalPracticeTime = parseInt(savedTotalTime);
            if (savedCompleted) state.completedPractices = parseInt(savedCompleted);
            if (savedStreak) state.streak = parseInt(savedStreak);
            if (savedStars) state.stars = parseInt(savedStars);
            
            updateProgressDisplay();
        }
        
        // 保存练习进度
        function saveProgress() {
            localStorage.setItem('totalPracticeTime', state.totalPracticeTime);
            localStorage.setItem('completedPractices', state.completedPractices);
            localStorage.setItem('practiceStreak', state.streak);
            localStorage.setItem('practiceStars', state.stars);
        }
        
        // 更新进度显示
        function updateProgressDisplay() {
            elements.streakCount.textContent = state.streak;
            elements.totalTime.textContent = state.totalPracticeTime;
            elements.starsCount.textContent = state.stars;
            elements.completedCount.textContent = state.completedPractices;
        }
        
        // 重置练习进度
        function resetProgress() {
            if (confirm('确定要重置所有练习进度吗？这将清除所有统计数据。')) {
                state.totalPracticeTime = 0;
                state.completedPractices = 0;
                state.streak = 0;
                state.stars = 0;
                
                localStorage.removeItem('totalPracticeTime');
                localStorage.removeItem('completedPractices');
                localStorage.removeItem('practiceStreak');
                localStorage.removeItem('practiceStars');
                localStorage.removeItem('lastPracticeDate');
                
                updateProgressDisplay();
                elements.settingsModal.classList.add('hidden');
            }
        }
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>
